package com.example.saifly.inPageRecord;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;
import com.example.saifly.inPageRecord.EnvironmentHistoryData.EnvironmentHistoryHumidActivity;
import com.example.saifly.inPageRecord.EnvironmentHistoryData.EnvironmentHistoryPm25Activity;
import com.example.saifly.inPageRecord.EnvironmentHistoryData.EnvironmentHistoryTemperatureActivity;
import com.example.saifly.inPageRecord.RecordModel.EnvironmentData;

import java.io.IOException;
import java.util.Date;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class EnvironmentActivity extends Activity {

    @Override
    protected int getContentLayoutId()
    {
        return R.layout.activity_record_environment_data;
    }

    TextView tvHeat,tvHumity,tvPm,tvSuggest;//tv展示各项指标
    private RelativeLayout rlEnvironmentTemperature,rlEnvironmentHumid,rlEnvironmentPm25;
    ImageView ivReturn;
    String suggestion;//总的建议
    String heatSuggestion,humitySuggestion,pmSuggestion;//各项的建议；

    int heat,humity,pm;//获取环境指标
    private SharedPreferences sharedPreferences;

    @Override
    protected void init() {
        super.init();
        sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        tvHumity=findViewById(R.id.record_environment_humidity_show);
        tvHeat=findViewById(R.id.record_environment_heat_show);
        tvPm=findViewById(R.id.record_environment_pm25_show);
        ivReturn=findViewById(R.id.environmentData_return);
        tvSuggest=findViewById(R.id.record_environment_suggest);
        heat=0;
        humity=0;
        pm=0;
        updateUi();
        rlEnvironmentTemperature=findViewById(R.id.environment_data_temperature);
        rlEnvironmentHumid=findViewById(R.id.environment_data_humidity);
        rlEnvironmentPm25=findViewById(R.id.environment_data_pm25);
        doJump();
    }

    private  void doJump()
    {
        ivReturn.setOnClickListener(view -> finish());
        rlEnvironmentTemperature.setOnClickListener(v -> startActivity(new Intent(this, EnvironmentHistoryTemperatureActivity.class)));
        rlEnvironmentHumid.setOnClickListener(v -> startActivity(new Intent(this, EnvironmentHistoryHumidActivity.class)));
        rlEnvironmentPm25.setOnClickListener(v -> startActivity(new Intent(this, EnvironmentHistoryPm25Activity.class)));
    }
    private int getDate(String str)
    {
        int temp;
        String tmp="";
        for(int i=0;i<str.length();i++)
        {
            if (str.charAt(i)>'9'||str.charAt(i)<'0') {
                break;
            }
            else
            {
                tmp+=str.charAt(i);
            }
        }
        temp=Integer.parseInt(tmp);
        return temp;
    }

    private  String analyse()
    {


        String message="";
        heat=getDate(tvHeat.getText().toString());
        humity=getDate(tvHumity.getText().toString());
        pm=getDate(tvPm.getText().toString());
        Log.d("humidity", "analyse: "+pm+humity+heat);
        if(heat==0)
        {
            message+="";
        }
        else if(heat<10)
        {
            message+="天气寒冷，注意做好保暖工作；";
        }
        else if(heat>9&&heat<20)
        {
            message+="天气比较凉爽，出汗时脱衣容易感冒，出汗时，尽量不要脱去衣物；";
        }
        else if(heat>19&&heat<30)
        {
            message+="温度比较舒适，空气良好的情况下，建议外出运动；";
        }
        else if(heat>=30)
        {
            message+="天气炎热，注意避暑；";
        }

        if(humity==0)
        {
            message+="";
        }
        else if(humity<30&&humity>=10)
        {
            message+="室内空气干燥，建议采取曾湿措施；";
        }
        else if(humity<10)
        {
            message+="室内空气非常干燥，建议尽快采取曾湿措施；";
        }
        else if(humity>70&&humity<=90)
        {
            message+="室内空气过于潮气，会让人感到很闷，建议尽快采取除湿措施；";
        }
        else if(humity>90)
        {
            message+="室内空气过于潮气，会让人感到很闷，建议尽快采取除湿措施；";
        }
        else if(humity>=30&&humity<=70)
        {
            message="室内空气湿度适宜，保持良好的室内湿度，有益于您的身体健康；";
        }

        if(pm==0)
        {
            message+="";
        }
        else if(pm<=35&&pm>0)
        {
            message+="室内pm2.5处于优秀状态，优秀的空气有助于您病情的恢复；";
        }
        else if(pm>35)
        {
            message+="室内pm2.5处于良好状态，对您病情的恢复几乎没有影响，也要做好室内除尘工作；";
        }
        else if(pm>75)
        {
            message+="室内pm2.5处于轻度污染，对您病情的恢复造成轻度影响，请做好室内除尘工作；";
        }
        else if(pm>115)
        {
            message+="室内pm2.5处于中度污染，对您病情的恢复造成中度影响，请尽快对室内进行除尘工作；";
        }
        return message;
    }

    private void  updateUi()
    {
        String phoneNum = sharedPreferences.getString("uid", "default");
        Date date =new Date();
        new Thread(new Runnable() {
            @Override
            public void run() {
                EnvironmentGetData(phoneNum,date);

            }
        }).start();

    }

    private interface ApiEnvironmentSetData
    {

        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getEnvironmentData")///
        Call<ResponseBody> EnvironmentGetData(@Body JSONObject jsonObject);

    }

    private void EnvironmentGetData(String patient_phone, Date date)
    {
        Long dateLong = date.getTime();
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiEnvironmentSetData apiEnvironmentSetData=retrofit.create(ApiEnvironmentSetData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",patient_phone);
        jsonObject.put("date",dateLong);
        Log.d("getdate", "EnvironmentGetData: "+jsonObject.toString());

        Call<ResponseBody> call=apiEnvironmentSetData.EnvironmentGetData(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    //  dailyQesFinish = (int) result.get("result");
                    JSONObject resultJson=result.getJSONObject("result");
                    String resultData=resultJson.getString("environmentData");
                    EnvironmentData environmentData=JSON.parseObject(resultData, EnvironmentData.class);

                    Log.d("resultxx", "EnvironmentGetData: "+environmentData);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(environmentData.getTemperature()==-200)
                            {
                                tvHeat.setText("0℃");
                            }
                            else
                            {
                                tvHeat.setText(environmentData.getTemperature().toString()+"℃");
                            }
                            tvPm.setText(environmentData.getPm25().toString()+"微克");
                            tvHumity.setText(environmentData.getHumidity().toString()+"%");
                            String temp=analyse();
                            if(temp.length()==0)
                            {
                                suggestion="此建议仅根据环境数据给出："+"今日数据尚未录入";
                            }
                            else
                            {
                                suggestion="此建议仅根据环境数据给出："+temp;
                            }
                            tvSuggest.setText(suggestion);


                        }
                    });
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(EnvironmentActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(EnvironmentActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }

    }


}
